package com.xyzwps.harbor.handler;

import com.xyzwps.harbor.handler.filter.AuthFilter;
import com.xyzwps.harbor.model.User;
import com.xyzwps.harbor.util.Dict;
import com.xyzwps.harbor.util.HarborException;
import org.springframework.web.reactive.function.server.ServerRequest;

public class RequestAttrs {

    public static User getUser(ServerRequest req) {
        var optionalUser = req.attribute(Dict.REQ_USER_INFO);
        if (optionalUser.isEmpty()) {
            throw HarborException.incorrectCode("you may not use " + AuthFilter.class.getSimpleName());
        }
        var user = optionalUser.get();
        if (user instanceof User) {
            return (User) user;
        } else {
            throw HarborException.incorrectCode("Attr[" + Dict.REQ_USER_INFO + "] is not a " + User.class.getSimpleName());
        }
    }
}
